package com.example.newspublish.filter;

import com.example.newspublish.util.JwtTokenManager;
import com.example.newspublish.util.ResponseUtils;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.http.HttpMethod;
import java.io.IOException;
@Component
public class AuthenticationFilter extends OncePerRequestFilter {
    private static final String TOKEN_PREFIX = "Bearer ";

    @Autowired
    private JwtTokenManager jwtTokenManager;

    public AuthenticationFilter(JwtTokenManager jwtTokenManager) {
        this.jwtTokenManager = jwtTokenManager;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        if(HttpMethod.OPTIONS.matches(request.getMethod()) ){
            chain.doFilter(request, response);
            return;
        }
        String header = request.getHeader("Authorization");
        System.out.println("开始过滤...");
//        String token = header.substring(TOKEN_PREFIX.length());
        if (header != null) {
            if(header.startsWith(TOKEN_PREFIX)) {
                try {
                    System.out.println("请求头正确...");
                    String token = header.substring(TOKEN_PREFIX.length());
                    System.out.println("请求填写token:"+token);
                    if (this.jwtTokenManager.validateToken(token)) {
                        System.out.println("JWT正确...");
                        Authentication authentication = this.jwtTokenManager.getAuthentication(token);
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                        chain.doFilter(request, response);
                    }
                    else {
                        System.out.println("JWT错误...");
                        ResponseUtils.writeErrMsg(response);
                    }
                }catch (Exception e){
                    System.out.println("出现异常"+e);
                    ResponseUtils.writeErrMsg(response);
                }
            }
            else {
                System.out.println("请求头错误...");
                ResponseUtils.writeErrMsg(response);
            }
        }
        else {
            System.out.println("无需token...");
            chain.doFilter(request, response);
            System.out.println("放行...");
        }

    }
}
